package com.jt.auth.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RemoteUserService  remoteUserService;
    /**
     * 基于用户查询
     * @param username 这个username 来自客户端
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
                            throws UsernameNotFoundException {

        //1.基于用户查询用户信息（暂时先给假数据）
        //Userinfo info = userMapper.selectUserByUsername(username);
//        String encodePassword = //假设这个密码来自数据库
//                passwordEncoder.encode("123456");

        //1.基于用户名查询用户信息(用户名,用户状态,密码,....)
        com.jt.auth.pojo.User user=
                remoteUserService.selectUserByUsername(username);
        if (user == null) throw new UsernameNotFoundException("用户不存在");


        //2.封装用户相关信息(用户名,密码，用户权限信息等)并返回
//        return new User(username,
//                encodePassword, //必须是已经加密的密码
//                AuthorityUtils.createAuthorityList( //这里的权限后面讲
//                        "sys:res:create","sys:res:retrieve"));

        //2.查询用户权限信息(后面会访问数据库)
        List<String> permissions =
                 remoteUserService.selectUserPermissions(user.getId());
        System.out.println("permissions="+permissions);

        List<GrantedAuthority> authorities =
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{}));

        //3.对用户信息进行封装
        return new User(username, user.getPassword(), authorities);

    }
}
